import {unbindindCloudPrinterClientId} from "../api/webSocket";
let rec; //断线重连后，延迟5秒重新创建WebSocket连接  rec用来存储延迟请求的代码
let lockReconnect = false; //连接标识 避免重复连接
const path = require('path');
let socket = null;
let globalCallback = function () {};
import store from '../store'
import {getStore} from "./storage";
const notification = {
    title: '主要标题',
    body: '本次推送由 云印小栈 提供',
    icon: require('../assets/programming.png')
};

const heartCheck = {
    timeout: 60000, //每段时间发送一次心跳包 60s
    timeoutObj: null, //延时发送消息对象（启动心跳新建这个对象，收到消息后重置对象）
    serverTimeoutObj: null,
    start: function () {
        this.timeoutObj && clearInterval(this.timeoutObj);
        this.timeoutObj = setInterval(function () {
            socket.send('heartbeat');
        }, this.timeout);
    },
    reset: function () {
        clearInterval(this.timeoutObj);
        this.start();
    }
};

export function init() {
    socket = new WebSocket(process.env.VUE_APP_WS_API);
    socket.onmessage = (e) => {
        getWebsocketMessage(e)
    };
    socket.onclose = (e) => {
        websocketClose(e)
    };
    socket.onopen = (e) => {
        websocketOpen()
    };

    // 连接发生错误的回调方法
    socket.onerror = function () {
        console.error('WebSocket连接发生错误');
        lockReconnect = false;
        reConnect();
    }
}

// 数据接收
function getWebsocketMessage (e) {
    const data = JSON.parse(e.data);
    if (!data) { heartCheck.reset(); }
    else { globalCallback && globalCallback(data) }

}

// 数据发送
function websocketSend (agentData) {
    socket.send(agentData)
}

// 关闭
function websocketClose (e) {
    console.log(`connection closed (${e}) `);
    unbindindCloudPrinterClientId().then(res => {
        new window.Notification('解绑设备', notification)
    })
   init()
}

// 创建 websocket 连接
function websocketOpen (e) {
    console.log('连接成功');
    heartCheck.start()
}
// 实际调用的方法
// agentData 发送数据
// callback 回调事件
function sendSock (agentData, callback) {
    globalCallback = callback;
    if (socket.readyState === socket.OPEN) {
        // 若是ws开启状态
        websocketSend(agentData)
    } else if (socket.readyState === socket.CONNECTING) {
        // 若是 正在开启状态，则等待1s后重新调用
        setTimeout(function () {
            sendSock(agentData, callback)
        }, 1000)
    } else {
        init();
        // 若未开启 ，则等待1s后重新调用
        setTimeout(function () {
            sendSock(agentData, callback)
        }, 1000)
    }
}

export function reConnect() {
    console.log("尝试重新连接");
    if (lockReconnect) return; //如果已经连上就不在重连了
    lockReconnect = true;
    // 没连接上会一直重连，设置延迟避免请求过多
    rec && clearTimeout(rec);
    rec = setTimeout(function () { // 延迟5秒重连  避免过多次过频繁请求重连
        init();
        lockReconnect = false
    }, 5000);
}

export function getSock(callback) {
    globalCallback = callback
}

// 将方法暴露出去
export {
    sendSock
}
